#ifndef PAGEDEVICEMGMT_H
#define PAGEDEVICEMGMT_H

#include <QWidget>
#include "core/databasepool/databasepool.h"
#include "core/threadpool/threadpool.h"
#include "modules/user-management/usermanagement.h"
#include "modules/device-management/devicemanagement.h"
#include "modules/data-monitor/datamonitor.h"
#include "modules/alert-manager/alertmanager.h"
#include "modules/data-analysis/dataanalysis.h"
#include "LogManager.h"
#include "mainbar.h"
#include <QSqlTableModel>
#include <QTableView>
#include <QDialog>
#include <QDateEdit>
#include <QVBoxLayout>
#include <QSortFilterProxyModel>
#include <QStyledItemDelegate>
#include <QDateTime>
#include <QMutex>

namespace Ui {
class pageDeviceMgmt;
}

class StatusDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit StatusDelegate(QObject *parent = nullptr);
    QWidget* createEditor(QWidget *parent,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const override;

    void setEditorData(QWidget *editor, const QModelIndex &index) const override;
    void setModelData(QWidget *editor,
                      QAbstractItemModel *model,
                      const QModelIndex &index) const override;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
};

class pageDeviceMgmt : public QWidget
{
    Q_OBJECT

public:
    explicit pageDeviceMgmt(Mainbar *mainbar,QWidget *parent = nullptr);
    ~pageDeviceMgmt();

private slots:
    void receiveUsername(const QString &);
    void onSearch(const QString &text);
    void onDeleteDevice();
    void onSaveChanges();
    void refreshTable();
    void onAddDevice();

private:
    bool executeTransaction(std::function<bool()> operation);
    Ui::pageDeviceMgmt *ui;
    QSqlTableModel *m_model;
    QSortFilterProxyModel *m_proxyModel;
    DeviceManagement m_deviceMgr;
    LogManager* m_logManager;
    static QString loginUsername;
    QMap<QString, QVariant> userInfo;
    Mainbar *m_mainbar;
    UserManagement m_userMgr;
    // 互斥锁，用于线程安全
    QMutex m_mutex;

    class AddDeviceDialog : public QDialog
    {
    public:
        explicit AddDeviceDialog(QWidget *parent = nullptr);
        QLineEdit *nameEdit;
        QLineEdit *typeEdit;
        QLineEdit *locationEdit;
        QLineEdit *manufacturerEdit;
        QLineEdit *modelEdit;
        QDateEdit *dateEdit;
    };
};

#endif // PAGEDEVICEMGMT_H
